/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.material.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import org.springblade.common.annotation.ServiceLog;
import org.springblade.common.constant.TrainingOperateConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.material.entity.ElectronicInformationEntity;
import org.springblade.modules.material.excel.AdmissionTicketImporter;
import org.springblade.modules.material.excel.PaperImportExcel;
import org.springblade.modules.material.excel.PaperImporter;
import org.springblade.modules.material.service.IElectronicInformationService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.material.entity.AdmissionTicketEntity;
import org.springblade.modules.material.vo.AdmissionTicketVO;
import org.springblade.modules.material.excel.AdmissionTicketExcel;
import org.springblade.modules.material.wrapper.AdmissionTicketWrapper;
import org.springblade.modules.material.service.IAdmissionTicketService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * 准考证 控制器
 *
 * @author junxin
 * @since 2024-01-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-admissionTicket/admissionTicket")
@Api(value = "准考证", tags = "准考证接口")
public class AdmissionTicketController extends BladeController {

	private final IAdmissionTicketService admissionTicketService;
	private final IElectronicInformationService electronicInformationService;

	/**
	 * 准考证 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入admissionTicket")
	public R<AdmissionTicketVO> detail(AdmissionTicketEntity admissionTicket) {
		AdmissionTicketEntity detail = admissionTicketService.getOne(Condition.getQueryWrapper(admissionTicket));
		return R.data(AdmissionTicketWrapper.build().entityVO(detail));
	}

	/**
	 * 准考证 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "无照片的人员分页", notes = "可传version、examSubject、userName、idCard、isNotImg=1 无电子照片的数据")
	public R<IPage<AdmissionTicketVO>> list(AdmissionTicketVO admissionTicket, Query query) {
		LambdaQueryWrapper<AdmissionTicketEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		if (Func.isNotEmpty(admissionTicket.getVersion())) lambdaQueryWrapper.like(AdmissionTicketEntity::getVersion,admissionTicket.getVersion());
		if (Func.isNotEmpty(admissionTicket.getExamSubject())) lambdaQueryWrapper.like(AdmissionTicketEntity::getExamSubject,admissionTicket.getExamSubject());
		if (Func.isNotEmpty(admissionTicket.getUserName())) lambdaQueryWrapper.like(AdmissionTicketEntity::getUserName,admissionTicket.getUserName());
		if (Func.isNotEmpty(admissionTicket.getIdCard())) lambdaQueryWrapper.like(AdmissionTicketEntity::getIdCard,admissionTicket.getIdCard());
		if (Func.isNotEmpty(admissionTicket.getYear())) lambdaQueryWrapper.like(AdmissionTicketEntity::getYear,admissionTicket.getYear());

		//查询无电子照片的数据
		if (Func.isNotEmpty(admissionTicket.getIsNotImg()) && 1==admissionTicket.getIsNotImg() ){
			List<ElectronicInformationEntity> informationList = electronicInformationService.list();
			if (Func.isNotEmpty(informationList)) {
				List<String> idCardList = informationList.stream().map(ElectronicInformationEntity::getIdCard).collect(Collectors.toList());
				if (Func.isNotEmpty(idCardList)) lambdaQueryWrapper.notIn(AdmissionTicketEntity::getIdCard,idCardList);

			}
		}

		IPage<AdmissionTicketEntity> pages = admissionTicketService.page(Condition.getPage(query),lambdaQueryWrapper);
		return R.data(AdmissionTicketWrapper.build().pageVO(pages));
	}


	/**
	 * 准考证 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入admissionTicket")
	public R save(@Valid @RequestBody AdmissionTicketEntity admissionTicket) {
		return R.status(admissionTicketService.save(admissionTicket));
	}

	/**
	 * 准考证 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入admissionTicket")
	public R update(@Valid @RequestBody AdmissionTicketEntity admissionTicket) {
		return R.status(admissionTicketService.updateById(admissionTicket));
	}


	/**
	 * 上传图片转base64
	 */
	@SneakyThrows
	@PostMapping("/img-to-base64")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "上传图片转base64", notes = "")
	public R uploadImgToBase64(@RequestParam("file") MultipartFile file ) {
		byte[] fileContent = file.getBytes();
		return R.data( Base64.encodeBase64String(fileContent));
	}

	/**
	 * 图片确认
	 */
	@PostMapping("/user-img-save")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "图片保存", notes = "传入id和userImg")
	@Transactional(rollbackFor = Exception.class)
	public R userImgSave(@Valid @RequestBody AdmissionTicketEntity admissionTicket ) {

		if (Func.isEmpty(admissionTicket.getId())) {
			throw new ServiceException("参数异常");
		}
		if (Func.isEmpty(admissionTicket.getUserImg())) {
			throw new ServiceException("图片不能为空");
		}
		AdmissionTicketEntity oldData = admissionTicketService.getById(admissionTicket);
		oldData.setUserImg(admissionTicket.getUserImg());
		admissionTicketService.updateById(oldData);

		if (Func.isNotEmpty(oldData.getIdCard())) {
			ElectronicInformationEntity electronicInformationEntity = electronicInformationService.getByIdcard(oldData.getIdCard());
			if (null==electronicInformationEntity){//如果为空则新增
				electronicInformationEntity=new ElectronicInformationEntity();
				electronicInformationEntity.setIdCard(oldData.getIdCard());
				electronicInformationEntity.setUserImg(admissionTicket.getUserImg());
				electronicInformationService.save(electronicInformationEntity);
			}else {//如果不为空 则覆盖
				electronicInformationEntity.setUserImg(admissionTicket.getUserImg());
				electronicInformationService.updateById(electronicInformationEntity);
			}

			LambdaUpdateWrapper<AdmissionTicketEntity> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
			lambdaUpdateWrapper.set(AdmissionTicketEntity::getUserImg,admissionTicket.getUserImg());
			lambdaUpdateWrapper.eq(AdmissionTicketEntity::getIdCard,oldData.getIdCard());
			admissionTicketService.update(lambdaUpdateWrapper);
		}


		return R.success("操作成功");
	}


	/**
	 * 准考证 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(admissionTicketService.deleteLogic(Func.toLongList(ids)));
	}



	/**
	 * 批量导入试题
	 */
	@PostMapping("import")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导入人员信息", notes = "传入excel")
	@ServiceLog(value = TrainingOperateConstant.EXAM,operate = TrainingOperateConstant.IMPORT,describe = "导入人员准考证信息")
	public R importQuestionBank(MultipartFile file) {
		AdmissionTicketImporter admissionTicketImporter = new AdmissionTicketImporter(admissionTicketService,electronicInformationService);
		ExcelUtil.save(file, admissionTicketImporter, AdmissionTicketExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<AdmissionTicketExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "准考证人员信息模板", "准考证模板", list, AdmissionTicketExcel.class);
	}


	/**
	 * 按照批次号导出
	 */
	@SneakyThrows
	@GetMapping("/exportByVersion")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "按照批次号导出列表", notes = "")
	public R exportByVersion(String verison ) {
		if (Func.isEmpty(verison)) {
			throw new ServiceException("请输入批次号!");
		}

		return R.data(admissionTicketService.list(Wrappers.<AdmissionTicketEntity>query().lambda().eq(AdmissionTicketEntity::getVersion,verison)));
	}


	/**
	 * 导出数据
	 */
	@GetMapping("/export-admissionTicket")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "导出数据", notes = "传入admissionTicket")
	public void exportAdmissionTicket(@ApiIgnore @RequestParam Map<String, Object> admissionTicket, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<AdmissionTicketEntity> queryWrapper = Condition.getQueryWrapper(admissionTicket, AdmissionTicketEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(AdmissionTicket::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(AdmissionTicketEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<AdmissionTicketExcel> list = admissionTicketService.exportAdmissionTicket(queryWrapper);
		ExcelUtil.export(response, "准考证数据" + DateUtil.time(), "准考证数据表", list, AdmissionTicketExcel.class);
	}

}
